<!DOCTYPE HTML>
<html>

<head>
    <meta charset="UTF-8">
    <title>WebSocket 聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            height: 100vh;
            background-color: #f5f5f5;
        }

        h1 {
            background-color: #007bff;
            color: white;
            padding: 20px;
            margin: 0;
            text-align: center;
            font-size: 24px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        #button-container {
            display: flex;
            gap: 10px;
            padding: 10px 20px;
            background-color: white;
            margin: 0 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        #main-container {
            display: flex;
            flex: 1;
            gap: 20px;
            padding: 20px;
            background-color: white;
            margin: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        #history-container {
            flex: 1;
            border: 1px solid #ccc;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 8px;
            overflow-y: auto;
        }

        #chat-container {
            flex: 2;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        #message {
            flex: 1;
            border: 1px solid #ccc;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 8px;
            overflow-y: auto;
        }

        #online-users {
            min-height: 150px;
            border: 1px solid #ccc;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 8px;
            overflow: auto;
        }

        .message-bubble {
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 12px;
            position: relative;
            word-wrap: break-word;
        }

        .message-sent .message-bubble {
            background-color: #007bff;
            color: white;
            align-self: flex-end;
        }

        .message-received .message-bubble {
            background-color: #e9ecef;
            color: black;
            align-self: flex-start;
        }

        .message-system .message-bubble {
            background-color: #ff4444;
            color: white;
            align-self: center;
        }

        .message-time {
            font-size: 0.8em;
            color: #666;
            margin-top: 5px;
            text-align: right;
        }

        #input-container {
            display: flex;
            gap: 10px;
            padding: 10px 20px; /* 减少上下 padding */
            background-color: white;
            margin: 0 20px 20px 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            align-items: center; /* 垂直居中 */
        }

        input {
            flex: 1;
            padding: 6px 10px; /* 进一步减少上下 padding */
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 14px;
            height: 32px; /* 进一步降低高度 */
            box-sizing: border-box; /* 确保 padding 不影响高度 */
        }

        button {
            padding: 6px 12px; /* 进一步减少上下 padding */
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s ease;
            height: 32px; /* 进一步降低高度 */
            box-sizing: border-box; /* 确保 padding 不影响高度 */
        }

        button:hover {
            background-color: #0056b3;
        }

        #user-list {
            list-style-type: none;
            padding: 0;
            margin: 0;
        }

        #user-list li {
            padding: 8px;
            background-color: #e9ecef;
            margin-bottom: 8px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        #user-list li:hover {
            background-color: #d1d5d8;
        }

        /* 添加滚动条样式 */
        #message::-webkit-scrollbar,
        #history-container::-webkit-scrollbar,
        #online-users::-webkit-scrollbar {
            width: 8px;
        }

        #message::-webkit-scrollbar-track,
        #history-container::-webkit-scrollbar-track,
        #online-users::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        #message::-webkit-scrollbar-thumb,
        #history-container::-webkit-scrollbar-thumb,
        #online-users::-webkit-scrollbar-thumb {
            background: #ccc;
            border-radius: 4px;
        }

        #message::-webkit-scrollbar-thumb:hover,
        #history-container::-webkit-scrollbar-thumb:hover,
        #online-users::-webkit-scrollbar-thumb:hover {
            background: #999;
        }
        /* 添加在线用户列表更新动画 */
        #user-list {
            transition: all 0.3s ease;
        }

        /* 高亮新上线的用户 */
        .new-user {
            background-color: #d4edda !important;
            animation: highlight 2s;
        }

        @keyframes highlight {
            from { background-color: #d4edda; }
            to { background-color: #e9ecef; }
        }
    </style>
</head>

<body>
<h1>WebSocket 聊天室</h1>
<div id="button-container">
    <button onclick="connectWebSocket()">连接 WebSocket</button>
    <button onclick="closeWebSocket()">断开连接</button>
</div>
<div id="main-container">
    <div id="history-container">
        <h3>历史记录</h3>
        <div id="history"></div>
    </div>
    <div id="chat-container">
        <div id="message"></div>
        <div id="online-users">
            <h3>在线用户</h3>
            <ul id="user-list"></ul>
        </div>
    </div>
</div>
<div id="input-container">
    <input id="userName" type="text" placeholder="输入你的用户名" />
    <input id="text" type="text" placeholder="输入消息" />
    <input id="targetUser" type="text" placeholder="目标用户" readonly />
    <button onclick="send()">发送消息</button>
</div>
</body>
<script type="text/javascript">
    let websocket = null;
    let userName = null;

    // 连接 WebSocket
    function connectWebSocket() {
        if (websocket && websocket.readyState === WebSocket.OPEN) {
            alert("已经连接到WebSocket");
            return;
        }

        userName = document.getElementById('userName').value;
        if (!userName) {
            alert("请输入用户名称");
            return;
        }

        if ('WebSocket' in window) {
            websocket = new WebSocket(`ws://localhost:8080/chat/${userName}`);
        } else {
            alert('当前浏览器不支持 WebSocket');
            return;
        }

        websocket.onerror = () => displaySystemMessage("系统: 连接发生错误");
        websocket.onopen = () => {
            displaySystemMessage("系统: 连接成功！");
            requestOnlineUsers(); // 连接成功后立即请求在线用户列表
        };
        websocket.onmessage = handleMessage;
        websocket.onclose = () => displaySystemMessage("系统: 连接已关闭");

        window.onbeforeunload = () => websocket.close();
    }

    // 新增：请求在线用户列表
    function requestOnlineUsers() {
        if (websocket && websocket.readyState === WebSocket.OPEN) {
            websocket.send("在线用户列表");
        }
    }

    // 修改后的处理消息函数
    function handleMessage(event) {
        const message = event.data;
        console.log("收到消息：", message);

        if (message.startsWith("在线用户列表:")) {
            updateOnlineUsers(message);
        } else if (message.startsWith("【系统】")) {
            // 当收到系统消息（如用户加入/离开）时刷新列表
            if (message.includes("加入") || message.includes("离开")) {
                requestOnlineUsers();
            }
            displaySystemMessage(message);
        } else {
            try {
                const messageData = JSON.parse(message);
                const sender = messageData.fromUser || "系统";
                const content = messageData.content;
                displayMessage(sender, content, "received");
            } catch (e) {
                displaySystemMessage(message);
            }
        }
    }

    // 修改后的更新在线用户函数
    function updateOnlineUsers(message) {
        const userList = document.getElementById('user-list');
        userList.innerHTML = '';

        // 解析消息，提取用户列表
        const usersPart = message.split(":")[1];
        if (!usersPart) {
            const li = document.createElement('li');
            li.textContent = "暂无在线用户";
            userList.appendChild(li);
            return;
        }

        const users = usersPart.trim().split(",").filter(Boolean);

        // 过滤掉当前用户（本人）
        const filteredUsers = users.filter(user => user.trim() !== userName);

        if (filteredUsers.length === 0) {
            const li = document.createElement('li');
            li.textContent = "暂无其他在线用户";
            userList.appendChild(li);
        } else {
            filteredUsers.forEach(user => {
                const li = document.createElement('li');
                li.textContent = user.trim();
                li.style.cursor = "pointer";
                li.onclick = () => {
                    document.getElementById('targetUser').value = user.trim();
                    document.getElementById('text').focus();
                };
                userList.appendChild(li);
            });
        }
    }
    // 显示消息
    function displayMessage(sender, content, type) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}`;

        const bubbleDiv = document.createElement('div');
        bubbleDiv.className = "message-bubble";
        bubbleDiv.textContent = `${sender}: ${content}`;

        const timeDiv = document.createElement('div');
        timeDiv.className = "message-time";
        timeDiv.textContent = new Date().toLocaleTimeString();

        messageDiv.appendChild(bubbleDiv);
        messageDiv.appendChild(timeDiv);
        document.getElementById('message').appendChild(messageDiv);
        document.getElementById('message').scrollTop = document.getElementById('message').scrollHeight;
    }

    // 显示系统消息
    function displaySystemMessage(message) {
        displayMessage("系统", message, "system");
    }

    // 更新在线用户列表
    function updateOnlineUsers(message) {
        const userList = document.getElementById('user-list');
        userList.innerHTML = '';
        const users = message.split(":")[1].trim().split(",");

        // 过滤掉当前用户（本人）
        const filteredUsers = users.filter(user => user.trim() !== userName);

        filteredUsers.forEach(user => {
            const li = document.createElement('li');
            li.textContent = user.trim();
            li.style.cursor = "pointer";
            li.onclick = () => {
                document.getElementById('targetUser').value = user.trim(); // 设置目标用户
                document.getElementById('text').focus(); // 聚焦到消息输入框
            };
            userList.appendChild(li);
        });
        console.log("更新在线用户列表：", filteredUsers);
    }

    // 关闭 WebSocket
    function closeWebSocket() {
        if (websocket) {
            websocket.close();
        }
    }

    // 发送消息
    function send() {
        const targetUserName = document.getElementById('targetUser').value;
        if (!targetUserName) {
            alert("请选择目标用户");
            return;
        }
        if (targetUserName === userName) {
            alert("不能给自己发送消息");
            return;
        }
        const message = document.getElementById('text').value;
        if (!message) {
            alert("请输入消息内容");
            return;
        }
        if (websocket) {
            const messageData = {
                targetUser: targetUserName,
                content: message
            };
            websocket.send(JSON.stringify(messageData));
            displayMessage("你", `-> ${targetUserName}: ${message}`, "sent");
            document.getElementById('text').value = ""; // 清空输入框
        } else {
            alert("WebSocket 未连接");
        }
    }

    // 加载聊天记录
    window.onload = () => loadChatHistory();

    async function loadChatHistory() {
        try {
            const res = await fetch("http://localhost:8080/ChatHistory/listHistory?pageNumber=1&pageSize=1000");
            const json = await res.json();

            if (json.data?.records) {
                json.data.records.forEach(record => {
                    const message = `${record.fromUser} -> ${record.toUser}: ${record.content}`;
                    const historyDiv = document.createElement('div');
                    historyDiv.className = "message received";
                    historyDiv.innerHTML = `
                        <div class="message-bubble">${message}</div>
                        <div class="message-time">${new Date(record.createdAt).toLocaleString()}</div>
                    `;
                    document.getElementById('history').appendChild(historyDiv);
                });
            } else {
                console.log("没有聊天记录");
            }
        } catch (error) {
            console.error("加载聊天记录失败:", error);
        }
    }
</script>

</html>